package com.mallcloud.mall.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mallcloud.mall.admin.api.dto.SysOauthClientDetailsDTO;
import com.mallcloud.mall.admin.api.entity.SysOauthClientDetails;
import com.mallcloud.mall.admin.service.SysOauthClientDetailsService;
import com.mallcloud.mall.common.core.util.R;
import com.mallcloud.mall.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(tags = "客户端管理模块")
@RestController
@AllArgsConstructor
@RequestMapping("/client")
public class SysClientController {
	private final SysOauthClientDetailsService clientDetailsService;

	@ApiOperation("通过ID查询")
	@GetMapping("/{clientId}")
	public R<List<SysOauthClientDetails>> getByClientId(@PathVariable String clientId) {
		return R.ok(clientDetailsService.list(Wrappers.<SysOauthClientDetails>lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId)));
	}

	@ApiOperation("简单分页查询")
	@GetMapping("/page")
	public R<IPage<SysOauthClientDetails>> getOauthClientDetailsPage(Page page, SysOauthClientDetails sysOauthClientDetails) {
		return R.ok(clientDetailsService.queryPage(page, sysOauthClientDetails));
	}

	@ApiOperation("添加")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_client_add')")
	public R<Boolean> add(@Valid @RequestBody SysOauthClientDetailsDTO clientDetailsDTO) {
		return R.ok(clientDetailsService.saveClient(clientDetailsDTO));
	}

	@ApiOperation("删除")
	@DeleteMapping("/{clientId}")
	@PreAuthorize("@pms.hasPermission('sys_client_del')")
	public R<Boolean> removeById(@PathVariable String clientId) {
		return R.ok(clientDetailsService.removeByClientId(clientId));
	}

	@ApiOperation("编辑")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_client_edit')")
	public R<Boolean> update(@Valid @RequestBody SysOauthClientDetailsDTO clientDetailsDTO) {
		return R.ok(clientDetailsService.updateClientById(clientDetailsDTO));
	}

	@ApiOperation("通过ID查询")
	@Inner(false)
	@GetMapping("/getClientDetailsById/{clientId}")
	public R<SysOauthClientDetails> getClientDetailsById(@PathVariable String clientId) {
		return R.ok(clientDetailsService.getOne(Wrappers.<SysOauthClientDetails>lambdaQuery().eq(SysOauthClientDetails::getClientId, clientId), false));
	}

	@ApiOperation("查询全部客户端")
	@Inner(false)
	@GetMapping("/list")
	public R<List<SysOauthClientDetails>> listClients() {
		return R.ok(clientDetailsService.list());
	}

	@ApiOperation("同步缓存字典")
	@PutMapping("/sync")
	public R sync() {
		return clientDetailsService.syncClientCache();
	}

}
